#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2014 OpenWrt.org

START=99
STOP=99

USE_PROCD=1
PROG=/usr/sbin/ztk_service.py
CONFIG_NAME=ztk_service

config_instance()
{
	local Options
	local enabled
	local  HTTP_PORT
	local enabled
	local MQTT_HOST
	local MQTT_PORT
	local MQTT_TOPIC
	local DOOR_UART

	config_get  DOOR_UART   $1      DOOR_UART
	config_get  HTTP_PORT	$1	HTTP_PORT
	config_get  enabled	$1	enabled
	config_get  MQTT_HOST	$1	MQTT_HOST
	config_get  MQTT_PORT	$1	MQTT_PORT
	config_get  MQTT_TOPIC	$1	MQTT_TOPIC

	[ "${enabled}" = "0" ] && return 1


	#HTTP_PORT = int(sys.argv[1])
	#MQTT_HOST = sys.argv[2]
	#MQTT_PORT = int(sys.argv[3])
	#MQTT_TOPIC = sys.argv[4]

	Options="${HTTP_PORT} ${MQTT_HOST} ${MQTT_PORT} ${MQTT_TOPIC} ${DOOR_UART}"
	echo "param: ${Options}"
	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command ${Options}
	procd_close_instance
	echo "${CONFIG_NAME} config_instance start. $date" >> /var/log/${CONFIG_NAME}.log
}
start () {
	echo "${CONFIG_NAME} start. $date"
	echo "${CONFIG_NAME} start. $date" >> /var/log/${CONFIG_NAME}.log    
	start_service
}
service_triggers() {
        procd_add_reload_trigger "${CONFIG_NAME}"
}
stop()
{
	echo "${CONFIG_NAME} stop. $date"
	echo "${CONFIG_NAME} stop. $date" >> /var/log/${CONFIG_NAME}.log
	service_stop $PROG 
}
restart () {
	echo "restart ${CONFIG_NAME} $date "
        echo "restart ${CONFIG_NAME} $date " >> /var/log/${CONFIG_NAME}.log                                     
	stop 
	start
}
reload_service() {
	local rv=0
	ubus call "${CONFIG_NAME}" reload || rv=1
	restart
	return $rv
}
start_service () {
	echo "start_service ${CONFIG_NAME} $date "
	config_load "${CONFIG_NAME}"
	config_foreach config_instance ztk_service
}
